﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

/**
 * 创建时间：2014/7/15 11:58:34
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace CUWo.Common
{
    public class JSONHelper
    {
        public static T Deserialize<T>(string json)
        {
            T local = Activator.CreateInstance<T>();
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(local.GetType());
                try
                {
                    local = (T)serializer.ReadObject(stream);
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.Message, typeof(JSONHelper),MethodBase.GetCurrentMethod());
                }                
                stream.Close();
                stream.Dispose();
            }
            return local;
        }

        public static string Serialize<T>(T obj)
        {
            string result = string.Empty;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                try
                {
                    serializer.WriteObject(stream, obj);
                    result = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.Message, typeof(JSONHelper), MethodBase.GetCurrentMethod());
                }
                stream.Dispose();
            }
            return result;
        }
    }
}
